package com.sjh.lib_app.utils

import android.graphics.Color
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.BindingAdapter
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.SpanUtils
import com.noober.background.drawable.DrawableCreator
import java.math.BigDecimal
import java.text.DecimalFormat

object BindingUtils {
    /**
     * @param priceFormat 价格
     * @param isNotShowPre 是否不显示￥
     * @param isNotScale 是否不缩放文本
     * @param isShowThousandBitSymbol 是否不简写为万，开启后价格不论多少，都显示全部
     * @param zeroStyle 对于0的处理方式 如果传入值为1 则显示为 面议 如果为2 则在后面加个起字
     * @param detailIsMianyi 交易类型是否要直接显示面议，0显示面议 1显示原来的值(目前是知产业务线专用，其他业务线没看到有类似的)
     * @param isHasQi 当 显示 0元的 时候， 其否需要在后面 跟一个 “起” 字
     */
    @BindingAdapter(value = ["priceFormat", "isNotShowPre", "isShowThousandBitSymbol", "isNotScale", "isNotShowMianyi", "isHasQi", "detailIsMianyi"],
                    requireAll = false)
    @JvmStatic
    fun TextView.formatPrice(priceFormat: Any?,
                             isNotShowPre: Boolean = false,
                             isShowThousandBitSymbol: Boolean = false,
                             isNotScale: Boolean = false,
                             isNotShowMianyi: Boolean = false,
                             isHasQi: Boolean = true,
                             detailIsMianyi: Boolean = false) {
        val priceFormat1 = priceFormat.toString().toDoubleOrNull() ?: 0.toDouble()
        if (detailIsMianyi) {
            this.text = "面议"
            return
        }
        if (priceFormat1 <= 0.0) {
            if (!isNotShowMianyi) {
                this.text = "面议"
            } else {
                val su = SpanUtils()
                //是否显示前缀
                if (!isNotShowPre) {
                    su.append("¥ ")
                    if (!isNotScale) {
                        su.setFontSize((this.textSize * 0.7f).toInt())
                    }
                }
                if (isHasQi) {
                    su.append("0起")
                } else {
                    su.append("0.00")
                }

                this.text = su.create()
            }
            return
        }

        val su = SpanUtils()
        //是否显示前缀
        if (!isNotShowPre) {
            su.append("¥ ")
            if (!isNotScale) {
                su.setFontSize((this.textSize * 0.7f).toInt())
            }
        }
        if (isShowThousandBitSymbol || priceFormat1 < 10000) {
            //todo 不要千分符 有可能会要
            // var formatStr = DecimalFormat(",##0.00").format(BigDecimal(priceFormat1))
            var formatStr = DecimalFormat("##0.00").format(BigDecimal(priceFormat1))
            if (!isNotScale) {
                var arr = formatStr.split(".")
                su.append(arr[0])
                if (arr.size == 2) {
                    su.append(".")
                    su.append("${arr[1]}")
                    su.setFontSize((this.textSize * 0.75f).toInt())
                }
            } else {
                su.append(formatStr)
            }
        } else {
            var trail = "万"
            var unit = 10000
            if (priceFormat1 >= 10000_0000) {
                trail = "亿"
                unit = 10000_0000
            } else {
                trail = "万"
                unit = 10000
            }
            val sp = String.format("%.2f", priceFormat1 / unit).split(".")
            su.append(sp[0])
            if (sp.size == 1) {
                su.append(trail)
            } else {
                su.append(".")
                su.append("${sp[1]}$trail")
            }
            if (!isNotScale) {
                su.setFontSize((this.textSize * 0.75f).toInt())
            }
        }

        this.text = su.create()
    }

    /**
     * @param frontText 前缀文字
     * @param price 价格
     * @param isShowRmb 是否显示￥
     * @param scaleValue 缩放值
     * @param isShowSeparator 是否显示千位符，仅仅在不转换万的时候生效
     * @param isShowZero 对于0的处理方式   false为不显示 true为显示
     * @param isShowUnit 是否显示万，亿
     */
    @BindingAdapter(
        value = ["frontText", "price", "isShowRmb", "scaleValue", "isShowSeparator", "isShowZero", "isShowUnit"],
        requireAll = false
    )
    @JvmStatic
    fun TextView.formatPrice2(
        frontText: String? = null,
        price: Any?,
        isShowRmb: Boolean? = true,
        scaleValue: Float? = 0.85f,
        isShowSeparator: Boolean? = false,
        isShowZero: Boolean? = true,
        isShowUnit: Boolean? = false
    ) {
        val priceFormat1 = if (!paramsJudge(price)) 0.0 else {
            price.toString().replace(",", "").toDouble()
        }
        val isShowRmb = isShowRmb ?: true
        val scaleValue = scaleValue ?: 0.85f
        val isShowSeparator = isShowSeparator ?: false
        val isShowZero = isShowZero ?: true
        val isShowUnit = isShowUnit ?: false
        val su = SpanUtils()
        su.append(frontText ?: "")
        if (priceFormat1 <= 0) {
            when (isShowZero) {
                true -> {
                    //是否显示前缀
                    if (isShowRmb) {
                        su.append("¥ ")
                        if (scaleValue < 1) {
                            su.setFontSize((this.textSize * scaleValue).toInt())
                        }
                    }
                    su.append("0.")
                    su.append("00")
                    if (scaleValue < 1) {
                        su.setFontSize((this.textSize * scaleValue).toInt())
                    }
                    this.text = su.create()
                }
                false -> {
                    this.text = ""
                }
            }
            return
        }
        //是否显示前缀
        if (isShowRmb) {
            su.append("¥ ")
            if (scaleValue < 1) {
                su.setFontSize((this.textSize * scaleValue).toInt())
            }
        }
        when {
            (priceFormat1 < 10000 || !isShowUnit) -> {
                var formatStr = if (isShowSeparator) {
                    DecimalFormat(",##0.00").format(BigDecimal(priceFormat1))
                    //                    .replace("(0+?$)|(.00$)".toRegex(), "")

                } else {
                    String.format("%.2f", priceFormat1)
                    //                        .replace("(0+?$)|(.00$)".toRegex(), "")
                }
                var arr = formatStr.split(".")
                su.append(arr[0])
                if (arr.size == 2) {
                    su.append(".")
                    su.append("${arr[1]}")
                    if (scaleValue < 1) {
                        su.setFontSize((this.textSize * scaleValue).toInt())
                    }
                }
            }
            else -> {
                var priceUnit = if (priceFormat1 <= 100000000) 10000 else 100000000
                var stringUnit = if (priceFormat1 <= 100000000) "万" else "亿"
                val sp = String.format("%.2f", priceFormat1 / priceUnit)
                    .replace("(0+?$)|(.00$)".toRegex(), "").split(".")
                su.append(sp[0])
                if (sp.size == 1) {
                    su.append(stringUnit)
                } else {
                    su.append(".")
                    su.append("${sp[1]}${stringUnit}")
                }
                if (scaleValue < 1) {
                    su.setFontSize((this.textSize * scaleValue).toInt())
                }
            }
        }
        this.text = su.create()
    }

    /**
     * 判断参数是否能转换成float操作，如果不能，就返回false
     */
    private fun paramsJudge(value: Any?): Boolean {
        var flage = true
        if (value == null) {
            flage = false
            return flage
        }
        try {
            value.toString().replace(",", "").toDouble()
        } catch (e: NumberFormatException) {
            flage = false
        }
        return flage
    }

    private val trademarkColors =
        arrayOf(
            DrawableCreator.Builder().setCornersRadius(SizeUtils.dp2px(4f).toFloat())
                .setSolidColor(Color.parseColor("#82AFE3"))
                .build(),
            DrawableCreator.Builder().setCornersRadius(SizeUtils.dp2px(4f).toFloat())
                .setSolidColor(Color.parseColor("#F17171"))
                .build(),
            DrawableCreator.Builder().setCornersRadius(SizeUtils.dp2px(4f).toFloat())
                .setSolidColor(Color.parseColor("#E3C182"))
                .build(),
            DrawableCreator.Builder().setCornersRadius(SizeUtils.dp2px(4f).toFloat())
                .setSolidColor(Color.parseColor("#82E3C3"))
                .build(),
            DrawableCreator.Builder().setCornersRadius(SizeUtils.dp2px(4f).toFloat())
                .setSolidColor(Color.parseColor("#F29B7C"))
                .build(),
            DrawableCreator.Builder().setCornersRadius(SizeUtils.dp2px(4f).toFloat())
                .setSolidColor(Color.parseColor("#BA9CF3"))
                .build(),
            DrawableCreator.Builder().setCornersRadius(SizeUtils.dp2px(4f).toFloat())
                .setSolidColor(Color.parseColor("#99EBA3"))
                .build(),
            DrawableCreator.Builder().setCornersRadius(SizeUtils.dp2px(4f).toFloat())
                .setSolidColor(Color.parseColor("#919DFC"))
                .build()
        )

    @BindingAdapter(value = ["trademarkColorPosition"], requireAll = false)
    @JvmStatic
    fun trademarkBackground(view: ImageView, trademarkColorPosition: String?) {
        val index = try {
            if (trademarkColorPosition.isNullOrBlank()) {
                0
            } else {
                trademarkColorPosition.substring(trademarkColorPosition.length - 2)
                    .toInt() % trademarkColors.size
            }
        } catch (e: Exception) {
            0
        }
        view.background = trademarkColors[index]
    }



    /**
     * 对投诉建议的状态的判断
     * @param status 状态  123
     *
     */
    @BindingAdapter(value = ["status"], requireAll = false)
    @JvmStatic
    fun TextView.feedBackStatus(status: String? = "0") {
        val bg = DrawableCreator.Builder().setCornersRadius(SizeUtils.dp2px(11f).toFloat())
        when (status) {
            "1" -> {//待受理
                this.background = bg.setSolidColor(Color.parseColor("#EBF5FF")).build()
                this.text = "待受理"
                this.setTextColor(Color.parseColor("#007DFF"))
            }
            "2" -> {//受理中
                this.background = bg.setSolidColor(Color.parseColor("#EBF9F5")).build()
                this.text = "受理中"
                this.setTextColor(Color.parseColor("#00AF7D"))
            }
            "3" -> { //已完结
                this.background = bg.setSolidColor(Color.parseColor("#F4F5F8")).build()
                this.text = "已完结"
                this.setTextColor(Color.parseColor("#979797"))

            }
            else -> {//待受理
                this.background = bg.setSolidColor(Color.parseColor("#EBF5FF")).build()
                this.text = "待受理"
                this.setTextColor(Color.parseColor("#007DFF"))
            }
        }
    }


}
